/**
 * 
 */
package com.shine.cotrun.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 缓存类
 * @author zsy
 *
 */
public class CacheMap<T> {
	private long maxCacheTime;//最大缓存时间:默认30分钟
	public long maxCacheSize;//缓存池大小

	private Map<String, CacheElement> cacheMap = new HashMap<String, CacheElement>();//缓存Map
	
	public CacheMap(long maxCacheTime, long maxCacheSize) {
		this.maxCacheTime = maxCacheTime;
		this.maxCacheSize = maxCacheSize;
	}
	
	public CacheMap(long maxCacheTime) {
		this(maxCacheTime, 1000);
	}
	
	public CacheMap() {
		this(1800000, 1000);
	}
	
	/**
	 * 添加缓存数据
	 * @param key
	 * @param value
	 * @param maxCacheTime
	 */
	public void addCache(String key, T value) {
		if (key == null) {
			throw new IllegalArgumentException();
		}
		CacheElement ce = cacheMap.get(key);
		if (ce != null && ce.value != null && !ce.value.getClass().equals(value.getClass())) {
			throw new IllegalArgumentException("缓存类型冲突，缓存Key重复：" + key);
		}
		if (cacheMap.size() >= maxCacheSize) {//缓存池已满
			clearCache();
		}
		cacheMap.put(key, new CacheElement(value, maxCacheTime));
	}
	
	/**
	 * 取得缓存数据
	 * @param key
	 * @return
	 */
	public T getCache(String key) {
		if (key == null) {
			throw new IllegalArgumentException();
		}
		CacheElement ce = cacheMap.get(key);
		if (ce == null) {
			return null;
		}
		if (ce.isOvertime()) {//缓存数据已超时
			cacheMap.remove(key);
			return null;
		}
		return ce.value;
	}
	
	/**
	 * 清除缓存
	 */
	public void clearCache() {
		cacheMap.clear();
	}
	
	private class CacheElement {
		public long maxCacheTime;
		public T value;
		public long cacheTime;
		
		public CacheElement(T value, long maxCacheTime) {
			this.maxCacheTime = maxCacheTime;
			this.value = value;
			cacheTime = System.currentTimeMillis();
		}
		//缓存是否超时
		public boolean isOvertime() {
			return System.currentTimeMillis() - cacheTime > maxCacheTime;
		}
	}
}
